/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.customer.customerrelation.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.web.customer.customerinfo.CustomersInfoRestApi;
import org.opsli.api.web.customer.student.CustomersStudentRestApi;
import org.opsli.api.web.tenant.channel.TenantChannelRestApi;
import org.opsli.api.wrapper.customer.customerinfo.CustomersInfoModel;
import org.opsli.api.wrapper.customer.customerrelation.CustomerStudentRelationModel;
import org.opsli.api.wrapper.customer.customerrelation.CustomerStudentRelationQueryModel;
import org.opsli.api.wrapper.customer.student.CustomersStudentModel;
import org.opsli.common.utils.WrapperUtil;
import org.opsli.core.base.service.impl.CrudServiceImpl;
import org.opsli.core.persistence.Page;
import org.opsli.modulars.customer.customerinfo.entity.CustomersInfo;
import org.opsli.modulars.customer.customerinfo.service.ICustomersInfoService;
import org.opsli.modulars.customer.customerrelation.entity.CustomerStudentRelation;
import org.opsli.modulars.customer.customerrelation.mapper.CustomerStudentRelationMapper;
import org.opsli.modulars.customer.customerrelation.service.ICustomerStudentRelationService;
import org.opsli.modulars.customer.student.entity.CustomersStudent;
import org.opsli.modulars.customer.student.service.ICustomersStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 客户关系 Service Impl
 *
 * @author guagua
 * @date 2025-06-29 00:14:23
 */
@Slf4j
@Service
public class CustomerStudentRelationServiceImpl
        extends CrudServiceImpl<CustomerStudentRelationMapper, CustomerStudentRelation, CustomerStudentRelationModel>
        implements ICustomerStudentRelationService {

    @Resource
    TenantChannelRestApi tenantChannelRestApi;
    @Resource
    CustomersInfoRestApi customersInfoRestApi;
    @Resource
    CustomersStudentRestApi customersStudentRestApi;
    @Autowired
    private org.opsli.modulars.customer.record.service.CustomerRecordBusinessService customerRecordBusinessService;
    @Autowired(required = false)
    private CustomerStudentRelationMapper mapper;
    @Autowired
    private ICustomersInfoService customersInfoService;
    @Autowired
    private ICustomersStudentService customersStudentService;

    @Override
    public Page<CustomerStudentRelation, CustomerStudentRelationModel> findPageWithDetails(
            CustomerStudentRelationQueryModel queryModel, Integer pageNo, Integer pageSize,
            HttpServletRequest request) {

        // 构建查询条件
        QueryWrapper<CustomerStudentRelation> queryWrapper = buildQueryWrapper(queryModel, request);

        // 执行分页查询
        Page<CustomerStudentRelation, CustomerStudentRelationModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryWrapper);
        page = super.findPage(page);

        // 填充详细信息
        enrichWithDetails(page.getList());

        return page;
    }

    @Override
    public CustomerStudentRelationModel getWithDetails(String id) {
        CustomerStudentRelationModel model = super.get(id);
        if (model != null) {
            List<CustomerStudentRelationModel> singleList = new ArrayList<CustomerStudentRelationModel>();
            singleList.add(model);
            enrichWithDetails(singleList);
        }
        return model;
    }

    /**
     * 构建查询条件
     */
    private QueryWrapper<CustomerStudentRelation> buildQueryWrapper(CustomerStudentRelationQueryModel queryModel,
            HttpServletRequest request) {
        QueryWrapper<CustomerStudentRelation> queryWrapper = new QueryWrapper<CustomerStudentRelation>();

        if (queryModel == null) {
            return queryWrapper;
        }

        // 基础查询条件
        if (StrUtil.isNotBlank(queryModel.getCustomerId_EQ())) {
            queryWrapper.eq("customer_id", queryModel.getCustomerId_EQ());
        }
        if (StrUtil.isNotBlank(queryModel.getStudentId_EQ())) {
            queryWrapper.eq("student_id", queryModel.getStudentId_EQ());
        }
        if (StrUtil.isNotBlank(queryModel.getRelationType_EQ())) {
            queryWrapper.eq("relation_type", queryModel.getRelationType_EQ());
        }
        if (StrUtil.isNotBlank(queryModel.getIsPrimary_EQ())) {
            queryWrapper.eq("is_primary", queryModel.getIsPrimary_EQ());
        }

        // 时间范围查询
        if (StrUtil.isNotBlank(queryModel.getCreateTime_GE())) {
            queryWrapper.ge("create_time", queryModel.getCreateTime_GE());
        }
        if (StrUtil.isNotBlank(queryModel.getCreateTime_LE())) {
            queryWrapper.le("create_time", queryModel.getCreateTime_LE());
        }
        if (StrUtil.isNotBlank(queryModel.getCreateBy_EQ())) {
            queryWrapper.eq("create_by", queryModel.getCreateBy_EQ());
        }

        // 处理嵌套查询参数 - 客户信息
        if (queryModel.getCustomerQP() != null) {
            handleCustomerQuery(queryWrapper, queryModel.getCustomerQP(), request);
        }

        // 处理嵌套查询参数 - 学生信息
        if (queryModel.getStudentQP() != null) {
            handleStudentQuery(queryWrapper, queryModel.getStudentQP(), request);
        }

        return queryWrapper;
    }

    /**
     * 处理客户查询条件
     */
    private void handleCustomerQuery(QueryWrapper<CustomerStudentRelation> queryWrapper, CustomersInfoModel customerQP,
            HttpServletRequest request) {
        if (customerQP == null)
            return;

        // 构建客户查询条件
        QueryWrapper<org.opsli.modulars.customer.customerinfo.entity.CustomersInfo> customerQueryWrapper = new QueryWrapper<>();

        if (StrUtil.isNotBlank(customerQP.getName())) {
            customerQueryWrapper.like("name", customerQP.getName());
        }
        if (StrUtil.isNotBlank(customerQP.getPhone())) {
            customerQueryWrapper.like("phone", customerQP.getPhone());
        }
        if (StrUtil.isNotBlank(customerQP.getEmail())) {
            customerQueryWrapper.like("email", customerQP.getEmail());
        }
        if (StrUtil.isNotBlank(customerQP.getGender())) {
            customerQueryWrapper.eq("gender", customerQP.getGender());
        }

        // 获取符合条件的客户信息列表
        List<CustomersInfo> customerList = customersInfoService.findList(customerQueryWrapper);

        // 提取客户ID列表（Java 1.8兼容写法）
        List<String> customerIds = new ArrayList<String>();
        for (CustomersInfo customer : customerList) {
            customerIds.add(customer.getId());
        }

        if (!customerIds.isEmpty()) {
            queryWrapper.in("customer_id", customerIds);
        } else {
            // 如果没有符合条件的客户，则返回空结果
            queryWrapper.eq("1", "0");
        }
    }

    /**
     * 处理学生查询条件
     */
    private void handleStudentQuery(QueryWrapper<CustomerStudentRelation> queryWrapper, CustomersStudentModel studentQP,
            HttpServletRequest request) {
        if (studentQP == null)
            return;

        // 构建学生查询条件
        QueryWrapper<org.opsli.modulars.customer.student.entity.CustomersStudent> studentQueryWrapper = new QueryWrapper<org.opsli.modulars.customer.student.entity.CustomersStudent>();

        if (StrUtil.isNotBlank(request.getParameterMap().get("studentQP.name")[0])) {
            studentQueryWrapper.like("name", request.getParameterMap().get("studentQP.name")[0]);
        }

        if (StrUtil.isNotBlank(studentQP.getGrade())) {
            studentQueryWrapper.eq("grade", studentQP.getGrade());
        }
        if (StrUtil.isNotBlank(studentQP.getGender())) {
            studentQueryWrapper.eq("gender", studentQP.getGender());
        }
        if (StrUtil.isNotBlank(studentQP.getStatus())) {
            studentQueryWrapper.eq("status", studentQP.getStatus());
        }
        if (StrUtil.isNotBlank(studentQP.getSchool())) {
            studentQueryWrapper.like("school", studentQP.getSchool());
        }
        if (StrUtil.isNotBlank(studentQP.getClassName())) {
            studentQueryWrapper.eq("class_name", studentQP.getClassName());
        }
        if (StrUtil.isNotBlank(studentQP.getEducationType())) {
            studentQueryWrapper.eq("education_type", studentQP.getEducationType());
        }

        // 获取符合条件的学生信息列表
        List<CustomersStudent> studentList = customersStudentService.findList(studentQueryWrapper);

        // 提取学生ID列表（Java 1.8兼容写法）
        List<String> studentIds = new ArrayList<String>();
        for (CustomersStudent student : studentList) {
            studentIds.add(student.getId());
        }

        if (!studentIds.isEmpty()) {
            queryWrapper.in("student_id", studentIds);
        } else {
            // 如果没有符合条件的学生，则返回空结果
            queryWrapper.eq("1", "0");
        }
    }

    /**
     * 填充详细信息
     */
    private void enrichWithDetails(List<CustomerStudentRelationModel> relationList) {
        if (relationList == null || relationList.isEmpty()) {
            return;
        }

        // 收集所有的客户ID和学生ID
        List<String> customerIds = new ArrayList<>();
        List<String> studentIds = new ArrayList<>();

        for (CustomerStudentRelationModel relation : relationList) {
            String customerId = relation.getCustomerId();
            if (StrUtil.isNotBlank(customerId) && !customerIds.contains(customerId)) {
                customerIds.add(customerId);
            }

            String studentId = relation.getStudentId();
            if (StrUtil.isNotBlank(studentId) && !studentIds.contains(studentId)) {
                studentIds.add(studentId);
            }
        }

        // 批量查询客户信息
        // List<CustomersInfoModel> customerList = new ArrayList<>();
        // if (!customerIds.isEmpty()) {
        // List<CustomersInfoModel> customers =
        // WrapperUtil.transformInstance(customersInfoService.listByIds(customerIds),
        // CustomersInfoModel.class);
        // customerList.addAll(customers);
        // }
        Map<String, CustomersInfoModel> customerMap = new HashMap<>();
        if (!customerIds.isEmpty()) {
            List<CustomersInfoModel> customers = WrapperUtil
                    .transformInstance(customersInfoService.listByIds(customerIds), CustomersInfoModel.class);
            for (CustomersInfoModel customer : customers) {
                customerMap.put(customer.getId(), customer);
            }
        }

        // 批量查询学生信息
        // List<CustomersStudentModel> studentList = new ArrayList<>();
        // if (!studentIds.isEmpty()) {
        // List<CustomersStudentModel> students =
        // WrapperUtil.transformInstance(customersStudentService.listByIds(studentIds),
        // CustomersStudentModel.class);
        // studentList.addAll(students);
        // }
        Map<String, CustomersStudentModel> studentMap = new HashMap<>();
        if (!studentIds.isEmpty()) {
            List<CustomersStudentModel> students = WrapperUtil
                    .transformInstance(customersStudentService.listByIds(studentIds), CustomersStudentModel.class);
            for (CustomersStudentModel student : students) {
                studentMap.put(student.getId(), student);
            }
        }

        // 填充信息
        for (CustomerStudentRelationModel relation : relationList) {
            // 填充客户信息
            CustomersInfoModel customer = WrapperUtil.transformInstance(customerMap.get(relation.getCustomerId()),
                    CustomersInfoModel.class);
            if (customer != null) {
                relation.setCustomer(customer);
            }

            // 填充学生信息
            relation.setStudents(Collections.singletonList(studentMap.get(relation.getStudentId())));
        }
    }

}